<?php

namespace Home\Controller;

use Home\Controller\BaseController;

class UsersController extends BaseController {

    public function _initialize() {
        parent::_initialize();

        if (empty($this->user_id)) {
            $this->ajaxReturn(0, "请登录!", '', 101);
        }
    }

    //获取用户信息
    public function userInfo() {
        $userInfo = M()->field("u.user_token,u.nick_name,u.head_imgurl,u.phone")
                        ->table("ot_users as u ")
                        ->where(array('user_id' => $this->user_id))->find();

        if (!empty($userInfo)) {
            $userInfo['dog_card_num'] = M('Dog')->where(['is_del' => 0, 'user_id' => $this->user_id])->count();

            $userInfo['post_num'] = M('Post')->where(['is_del' => 0, 'user_id' => $this->user_id, 'post_type' => array('NEQ', 10)])->count();
            $userInfo['collect_num'] = M('PostCollect')->where(['user_id' => $this->user_id])->count();
            $userInfo['topic_collect_num'] = M('TopicFollow')->where(['user_id' => $this->user_id])->count();
            $userInfo['zan_num'] = M('PostZan')->where(['user_id' => $this->user_id, 'comment_id' => 0])->count();
            $userInfo['sale_num'] = M('Post')->where(['is_del' => 0, 'user_id' => $this->user_id, 'post_type' => 10])->count();


            $dogs = M('Dog')->where(['user_id' => $this->user_id, 'is_del' => 0])->getField('dog_id', true);
            $where['dog_id'] = array('in', $dogs);
            $where['status'] = 0;
            $userInfo['biaobai'] = M('Profess')->where($where)->count();
        }
        $this->success($userInfo);
    }

    //设置用户昵称
    public function setNickName() {
        $nickName = I('nickname');
        if (empty($nickName)) {
            $this->error("昵称不允许为空");
        }

        $data = array('nick_name' => $nickName);
        $res = M("Users")->where(array('user_id' => $this->user_id))->save($data);
        if ($res) {
            $this->success();
        } else {
            $this->error('修改失败');
        }
    }

    //设置用户头像
    public function setHeadImg() {
        $face = I('face');
        if (empty($face)) {
            $this->error("头像不允许为空");
        }

        $code = md5(time() + mt_rand(1, 9999));
        $s = file_put_contents('./Uploads/Picture/' . $code . '.png', base64_decode($face)); //返回的是字节数

        $face_url = '/Uploads/Picture/' . $code . '.png';

        $data = array('head_imgurl' => $face_url);
        $res = M("Users")->where(array('user_id' => $this->user_id))->save($data);

        if ($res) {
            $this->success();
        } else {
            $this->error('修改失败');
        }
    }

    public function setPhone() {
        $phone = I('phone');
        if (empty($phone)) {
            $this->error("请输入用户手机号");
        }

        $is_phone = M('Users')->where(['phone' => $phone])->find();

        if ($is_phone) {
            $this->error("该手机号已被占用");
        }

        $data['phone'] = $phone;
        $res = M("Users")->where(array('user_id' => $this->user_id))->save($data);

        if ($res) {
            $this->success();
        } else {
            $this->error('修改失败');
        }
    }

    public function getFollwong() {
        $p = I('p', 0, 'intval');
        $size = I('psize', 15, 'intval');
        if ($p) {
            $page = $p * $size;
        }

        $cache_data = S('follow_list_' . $this->user_id);
        $newlist = [];
        $cache_data = [];
        if (!$cache_data) {

            $follow_user = M('UserFollow')->where(['user_id' => $this->user_id])->getField('follow_uid', TRUE);

            $follow_user_dog = [];
            if (!empty($follow_user)) {
                $follow_user_where['user_id'] = array('in', $follow_user);
                $follow_user_dog = M('Dog')->where($follow_user_where)->getField('dog_id', TRUE);
            }


            $follow_topic_id = M()->table('ot_topic_follow tf')
                    ->join('ot_post p on p.topic_id = tf.topic_id')
                    ->where(['tf.user_id' => $this->user_id, 'p.is_del' => 0])
                    ->getField('post_id', true);


            $where = [];
            if (!empty($follow_user_dog)) {
                $where['t.dog_id'] = array('in', $follow_user_dog);

                $list = M('Track')
                        ->table('ot_track t')
                        ->field('t.*,d.dog_name,d.dog_face')
                        ->join('ot_dog d on t.dog_id = d.dog_id')
                        ->where($where)
                        ->order('create_time desc')
//                ->limit($page, $size)
                        ->select();
            } else {
                $list = [];
            }


            if (empty($list)) {
                $list = [];
            }

            if (!empty($follow_topic_id)) {
                $postwhere['p.post_id'] = array('in', $follow_topic_id);
                $post_list = M()->table('ot_post p')
                        ->field('p.post_id,p.title,p.post_type,p.post_style,p.topic_id,p.user_id,p.content,p.img_list,p.price,p.video_url,p.video_img,p.create_time,u.head_imgurl,u.nick_name,t.topic_name')
                        ->join('left join ot_topic t on p.topic_id = t.topic_id')
                        ->join('left join ot_users u on p.user_id = u.user_id')
                        ->where($postwhere)
                        ->order('p.create_time desc')
//                ->limit($page, $size)
                        ->select();
            } else {
                $post_list = [];
            }

            $follow_user_post = [];
            if (!empty($follow_user)) {
                $follow_user_where1['p.user_id'] = array('in', $follow_user);
                $follow_user_post = M()->table('ot_post p')
                        ->field('p.post_id,p.title,p.post_type,p.post_style,p.topic_id,p.user_id,p.content,p.img_list,p.price,p.video_url,p.video_img,p.create_time,u.head_imgurl,u.nick_name,t.topic_name')
                        ->join('left join ot_topic t on p.topic_id = t.topic_id')
                        ->join('left join ot_users u on p.user_id = u.user_id')
                        ->where($follow_user_where1)
                        ->order('p.create_time desc')
//                ->limit($page, $size)
                        ->select();
            } else {
                $follow_user_post = [];
            }


            foreach ($post_list as &$val) {
//            $val = formatPost($val, $this->user_id);
                $val['data_type'] = 2;
            }
            unset($val);

            foreach ($follow_user_post as &$val) {
//            $val = formatPost($val, $this->user_id);
                $val['data_type'] = 2;
            }
            unset($val);


            foreach ($list as &$val) {
                $val['data_type'] = 1;
            }
            unset($val);

            $new_post = array_merge($post_list, $follow_user_post);
            $new_post = array_unset_tt($new_post, 'post_id');

            $newlist = array_merge($new_post, $list);


            $newlist = $this->my_sort($newlist, 'create_time', SORT_DESC);

            S('follow_list_' . $this->user_id, $newlist, 300);
        } else {
            $newlist = $cache_data;
        }

        $newlist = array_slice($newlist, $page, $size);




        if (!empty($newlist)) {
            foreach ($newlist as &$val) {

                if ($val['data_type'] == 1) {
                    $val['dog_face'] = 'https://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $val['dog_face'];

                    $date = strtotime($val['create_time']);

                    $today = date('Y-m-d', time());
                    $zuotian = date("Y-m-d", strtotime("-1 day"));
                    $qiantian = date("Y-m-d", strtotime("-2 day"));
                    $create_time = date('Y-m-d', $date);

                    $date_time = date('H:i', $date);

                    if ($create_time == $today) {
                        $hours = intval((time() - $date) / 3600);
                        $val['create_date'] = '刚刚';
                        if ($hours >= 1) {
                            $val['create_date'] = $hours . '小时前';
                        }
                        $val['create_time'] = $date_time;
                    } elseif ($create_time == $zuotian) {
                        $val['create_date'] = '昨天';
                        $val['create_time'] = $date_time;
                    } elseif ($create_time == $qiantian) {
                        $val['create_date'] = '前天';
                        $val['create_time'] = $date_time;
                    } else {
                        $val['create_date'] = '3天前';
                        $val['create_time'] = '';
                    }

                    if ($val['type'] == 1) {
                        $dashang = M('Reward')
                                ->table('ot_reward r')
                                ->field('u.*,r.number,d.dog_name')
                                ->join('ot_users u on r.user_id = u.user_id')
                                ->join('ot_dog d on r.dog_id = d.dog_id')
                                ->where(['reward_id' => $val['relation_id']])
                                ->find();

                        if (!empty($dashang)) {
                            $val['content'] = $dashang['nick_name'] . '向' . $dashang['dog_name'] . '打赏' . $dashang['number'] . '两白银';
                            $val['user_id'] = $dashang['user_id'];
                            $val['relation_data'] = [];
                        }
                    }

                    if ($val['type'] == 2) {
                        $xiezhen = M('Photo')
                                ->field('photo_id,photo_url')
                                ->where(['group_id' => $val['relation_id']])
                                ->select();

                        if (!empty($xiezhen)) {

                            foreach ($xiezhen as &$photo) {
                                $photo['photo_url'] = 'https://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $photo['photo_url'];
                            }
                            unset($photo);

                            $val['content'] = $val['dog_name'] . '更新了写真集';
                            $val['relation_data'] = $xiezhen;
                        }
                    }

                    if ($val['type'] == 3) {
                        $biaobai = M()->table('ot_profess p')
                                ->join('ot_dog d on p.pro_dog_id = d.dog_id')
                                ->where(['p.profess_id' => $val['relation_id']])
                                ->find();

                        if (!empty($biaobai)) {
                            $val['content'] = $biaobai['dog_name'] . '向' . $val['dog_name'] . '表白,希望成为它的' . $biaobai['identity'];
                            $val['relation_data'] = [];
                        }
                    }
                } else {
                    $val = formatPost($val, $this->user_id);
                }
            }

            unset($val);
        } else {
            $newlist = [];
        }

        sleep(1);
        $this->success('获取成功', $newlist);
    }

    public function getMyPost() {
        $p = I('p', 0, 'intval');
        $size = I('psize', 15, 'intval');
        if ($p) {
            $page = $p * $size;
        }

        $where['p.is_del'] = 0;
        $where['p.user_id'] = $this->user_id;
        $where['p.post_type'] = array('neq', 10);


        $list = M()->table('ot_post p')
                ->field('p.post_id,p.title,p.post_type,p.user_id,p.content,p.img_list,p.video_url,p.create_time,t.topic_name,p.topic_id')
                ->join('left join ot_topic t on p.topic_id = t.topic_id')
                ->where($where)
                ->order('p.create_time desc')
                ->limit($page, $size)
                ->select();


        if ($list) {
            foreach ($list as &$val) {
                $strTime = strtotime($val['create_time']);
                $val['month'] = date('m', $strTime);
                $val['day'] = date('d', $strTime);

                if (!empty($val['img_list'])) {
                    $img_list = explode(',', $val['img_list']);

                    $new_img = [];
                    foreach ($img_list as $img) {
                        if (count($new_img) < 4) {
                            $new_img[] = 'https://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $img;
                        }
                    }

                    $val['img_list'] = $new_img;
                    $val['img_sum'] = count($img_list);
                } else {
                    $val['img_list'] = [];
                    $val['img_sum'] = 0;
                }

                if (!empty($val['video_url'])) {
                    $val['video_url'] = 'https://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $val['video_url'];
                }
            }

            unset($val);
        } else {
            $list = [];
        }

        $this->success('获取成功', $list);
    }

    public function getMySale() {
        $p = I('p', 0, 'intval');
        $size = I('psize', 15, 'intval');
        if ($p) {
            $page = $p * $size;
        }

        $where['p.is_del'] = 0;
        $where['p.user_id'] = $this->user_id;
        $where['p.post_type'] = 10;


        $list = M()->table('ot_post p')
                ->field('p.post_id,p.title,p.post_type,p.user_id,p.content,p.img_list,p.video_url,p.create_time')
                ->where($where)
                ->order('p.create_time desc')
                ->limit($page, $size)
                ->select();


        if ($list) {
            foreach ($list as &$val) {
                $strTime = strtotime($val['create_time']);
                $val['month'] = date('m', $strTime);
                $val['day'] = date('d', $strTime);

                if (!empty($val['img_list'])) {
                    $img_list = explode(',', $val['img_list']);

                    $new_img = [];
                    foreach ($img_list as $img) {
                        if (count($new_img) < 4) {
                            $new_img[] = 'https://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $img;
                        }
                    }

                    $val['img_list'] = $new_img;
                    $val['img_sum'] = count($img_list);
                } else {
                    $val['img_list'] = [];
                    $val['img_sum'] = 0;
                }

                if (!empty($val['video_url'])) {
                    $val['video_url'] = 'https://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $val['video_url'];
                }
            }

            unset($val);
        } else {
            $list = [];
        }

        $this->success('获取成功', $list);
    }

    public function getMyCollect() {
        $p = I('p', 0, 'intval');
        $size = I('psize', 15, 'intval');
        if ($p) {
            $page = $p * $size;
        }

        $where['p.is_del'] = 0;
        $where['pc.user_id'] = $this->user_id;

        $list = M()->table('ot_post_collect pc')
                ->field('pc.collect_id,p.post_id,p.title,p.post_type,p.user_id,p.content,p.img_list,p.video_url,pc.create_time')
                ->join('ot_post p on pc.post_id = p.post_id')
                ->where($where)
                ->order('pc.create_time desc')
                ->limit($page, $size)
                ->select();
        if ($list) {
            foreach ($list as &$val) {
                $strTime = strtotime($val['create_time']);
                $val['month'] = date('m', $strTime);
                $val['day'] = date('d', $strTime);
                $is_zan = M('PostZan')->where(['post_id' => $val['post_id'], 'user_id' => $this->user_id])->find();

                $val['is_zan'] = 0;
                if ($is_zan) {
                    $val['is_zan'] = 1;
                }

                $val['zan_num'] = M('PostZan')->where(['post_id' => $val['post_id']])->count();
                $val['comment_num'] = M('PostComment')->where(['post_id' => $val['post_id']])->count();

                if (!empty($val['img_list'])) {
                    $img_list = explode(',', $val['img_list']);

                    $new_img = [];
                    foreach ($img_list as $img) {
                        if (count($new_img) < 4) {
                            $new_img[] = 'https://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $img;
                        }
                    }

                    $val['img_list'] = $new_img;
                    $val['img_sum'] = count($img_list);
                } else {
                    $val['img_list'] = [];
                    $val['img_sum'] = 0;
                }

                if (!empty($val['video_url'])) {
                    $val['video_url'] = 'https://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $val['video_url'];
                }
            }
            unset($val);
        } else {
            $list = [];
        }

        $this->success('获取成功', $list);
    }

    function my_sort($arrays, $sort_key, $sort_order = SORT_ASC, $sort_type = SORT_STRING) {
        if (is_array($arrays)) {
            foreach ($arrays as $array) {
                if (is_array($array)) {
                    $key_arrays[] = $array[$sort_key];
                } else {
                    return false;
                }
            }
        } else {
            return false;
        }
        array_multisort($key_arrays, $sort_order, $sort_type, $arrays);
        return $arrays;
    }

    public function getFollowTopic() {
        $p = I('p', 0, 'intval');
        $page = 0;

        $size = I('psize', 15, 'intval');
        if ($p) {
            $page = $p * $size;
        }

        $topic_ids = M('TopicFollow')
                        ->table('ot_topic_follow tf')
                        ->join('right join ot_topic t on tf.topic_id = t.topic_id')
                        ->field('count(tfollow_id) as follow_number,t.topic_id')
                        ->where(['t.is_del' => 0, 'tf.user_id' => $this->user_id])
                        ->group('tf.topic_id')
                        ->limit($page, $size)
                        ->order('count(tfollow_id) desc')->select();

        $topic_list = [];
        foreach ($topic_ids as $id) {
            $topic_info = M('Topic')->where(['topic_id' => $id['topic_id']])->find();
            $id['topic_name'] = $topic_info['topic_name'];
            $id['follow_face'] = M()->table('ot_topic_follow tf')
                    ->join('left join ot_users u on tf.user_id = u.user_id')
                    ->where(['tf.topic_id' => $id['topic_id']])
                    ->limit(0, 4)
                    ->getField('head_imgurl', true);
            $id['topic_content'] = $topic_info['topic_content'];
            $id['topic_pic'] = 'https://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $topic_info['topic_pic'];
            $id['post_num'] = M('Post')->where(['topic_id' => $id['topic_id']])->count();
            $topic_list[] = $id;
        }
        $this->success('获取成功', $topic_list);
    }

    public function followOrCancel() {
        if ($this->user_id == 0) {
            $this->error('请登录', '', 101);
        }

        $follow_uid = I('follow_uid', 0, 'intval');

        if ($follow_uid == 0) {
            $this->error('请选择正确的用户');
        }

        $is_follow = M('UserFollow')->where(['follow_uid' => $follow_uid, 'user_id' => $this->user_id])->find();

        $res = 0;
        if ($is_follow) {
            $res = M('UserFollow')->where(['ufollow_id' => $is_follow['ufollow_id']])->delete();
        } else {
            $data['follow_uid'] = $follow_uid;
            $data['user_id'] = $this->user_id;
            $res = M('UserFollow')->add($data);
        }

        if ($res) {
            S('follow_list_' . $this->user_id, []);
            $this->success();
        } else {
            $this->error();
        }
    }

    public function getZanList() {
        $p = I('p', 0, 'intval');
        $size = I('psize', 15, 'intval');
        if ($p) {
            $page = $p * $size;
        }

        $where['p.is_del'] = 0;
        $where['pz.comment_id'] = 0;
        $where['pz.user_id'] = $this->user_id;

        $list = M()->table('ot_post_zan pz')
                ->field('pz.zan_id,p.post_id,p.title,p.post_type,p.user_id,p.content,p.img_list,p.video_url,pz.create_time')
                ->join('ot_post p on pz.post_id = p.post_id')
                ->where($where)
                ->order('pz.create_time desc')
                ->limit($page, $size)
                ->select();
        if ($list) {
            foreach ($list as &$val) {
                $strTime = strtotime($val['create_time']);
                $val['month'] = date('m', $strTime);
                $val['day'] = date('d', $strTime);

                $val['is_zan'] = 1;

                $val['zan_num'] = M('PostZan')->where(['post_id' => $val['post_id']])->count();
                $val['comment_num'] = M('PostComment')->where(['post_id' => $val['post_id']])->count();

                if (!empty($val['img_list'])) {
                    $img_list = explode(',', $val['img_list']);

                    $new_img = [];
                    foreach ($img_list as $img) {
                        if (count($new_img) < 4) {
                            $new_img[] = 'https://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $img;
                        }
                    }

                    $val['img_list'] = $new_img;
                    $val['img_sum'] = count($img_list);
                } else {
                    $val['img_list'] = [];
                    $val['img_sum'] = 0;
                }

                if (!empty($val['video_url'])) {
                    $val['video_url'] = 'https://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $val['video_url'];
                }
            }
            unset($val);
        } else {
            $list = [];
        }

        $this->success('获取成功', $list);
    }

}
